package server;

import server.commonData.Room;
import server.commonData.User;

import com.core.NetChannel;
import com.core.action.MessageAction;
import com.core.action.TimeAction;
import com.core.initialize.Message;
import com.core.interfaces.IScheduledThread;
import com.core.thread.BaseMessageExecutorPool;

/**
 * 按房间分线程的
 * 收到客户端的信息 如果玩家进入了房间 则消息会在房间的线程内执行 
 * 如果没有进入房间则玩家消息在 mainThread内执行
 * 尽量保证了线程安全
 * @author King
 *
 */
public class RoomMessageExecutor extends BaseMessageExecutorPool{

	private IScheduledThread mainThread;
	
	public RoomMessageExecutor()
	{
		int avaliableCpuNumber = Runtime.getRuntime().availableProcessors();
		for(int i =0;i<avaliableCpuNumber;i++)
			addThreadPoolExecutor();
		mainThread=getIndexExecutor();
	}
	
	
	@Override
	public IScheduledThread pushAction(Runnable serverAction)
	{
		if(serverAction instanceof TimeAction)
		{
			Thread.dumpStack();
			return null;
		}
		if(serverAction instanceof Room)
		{
			IScheduledThread executor =	getIndexExecutor();
			executor.pushAction((Room)serverAction);
			return executor;
		}
		
		if(serverAction instanceof MessageAction)
		{
			MessageAction action = (MessageAction)serverAction;
			Message msg = action.getMsg();
			NetChannel channel = msg.getChannel();
			if(channel==null)
			{
				mainThread.pushAction(serverAction);
				return mainThread;
			}
			User user = channel.getCahceInfo();
			if(user==null)
			{
				mainThread.pushAction(serverAction);
				return mainThread;
			}
			Room room = user.getRoom();
			if(room==null)
			{
				mainThread.pushAction(serverAction);
				return mainThread;
			}
			room.getExecutor().pushAction(serverAction);
			return room.getExecutor();
		}
		else
		{
			this.mainThread.pushAction(serverAction);
			return this.mainThread;
		}
	}
}
